package com.lijiayue.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lijiayue.mapper.StudentMapper;
import com.lijiayue.mapper.UserMapper;
import com.lijiayue.model.domain.Student;
import com.lijiayue.model.domain.User;
import com.lijiayue.service.UserService;
import com.lijiayue.util.JwtUtil;
import com.lijiayue.util.Md5Util;
import com.lijiayue.util.RedisConstant;
import com.lijiayue.util.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private StudentMapper studentMapper;

    /**
     * 用户注册
     */
    @Override
    public void userRegister(User user) throws InterruptedException {
        //同步学生（教师）表信息
        Student student = new Student();

        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(User::getUserName, user.getUserName());
        User userSql = this.getOne(userQueryWrapper);
        if (userSql != null) {
            //已经存在该用户
            throw new RuntimeException("用户名已存在");
        } else {
            String password = Md5Util.getMD5String(user.getPassWord());
            user.setPassWord(password);
            user.setId(IdUtil.getSnowflakeNextId());

            Thread thread = new Thread(() -> {
                if (user.getRole().equals("student")) {
                    student.setId(user.getId());
                    student.setName(user.getUserName());
                    student.setCreateTime(new Date());
                    studentMapper.insert(student);
                }
            }, "userRegister");

            thread.start();
            thread.join();

            boolean save = this.save(user);
            if (!save) {
                throw new RuntimeException("用户注册失败");
            }
        }
    }

    /**
     * 用户登录
     */
    @Override
    public Result<Map<String, Object>> userLogin(User user) {
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(User::getUserName, user.getUserName());
        User userSql = this.getOne(userQueryWrapper);

        //校验用户登录类型
        if (!user.getRole().equals(userSql.getRole())) {
            throw new RuntimeException("用户登录类型错误");
        }

        //不存在对应的用户
        if (userSql != null) {
            //MD5加密
            String password = Md5Util.getMD5String(user.getPassWord());
            //密码校验
            if (password.equals(userSql.getPassWord()) && userSql.getUserName().equals(user.getUserName())) {
                HashMap<String, Object> map = new HashMap<>();
                String token = JwtUtil.generateToken(user.getId(), user.getUserName());
                map.put("token", token);
                map.put("userId", userSql.getId());
                map.put("userName", userSql.getUserName());
                map.put("role", userSql.getRole());
                //先清除旧缓存
                redisTemplate.delete(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
                redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token, userSql, RedisConstant.TOKEN_TIME, TimeUnit.MINUTES);

                return Result.ok(map);
            } else {
                throw new RuntimeException("密码错误或用户名错误");
            }
        } else {
            throw new RuntimeException("用户不存在");
        }
    }
}
